#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
# @Time    : 2022/06/08 17:28
# @Author  : elegantfrog
# @FileName: utils.py

import json
import requests
import time
from functools import reduce
from redis import Redis, ConnectionPool
# from config import config
from utils.config import config
import base64


class aUtils():
    def __init__(self, req):
        self.resFormat = {}
        self.req = req
        self.default = './files/default.json'
        self.redisConfig = config['redis']
        try:
            self.redis_pool = ConnectionPool(host=self.redisConfig['host'], port=self.redisConfig['port'],
                                             password=self.redisConfig['password'], db=self.redisConfig['db'],
                                             max_connections=self.redisConfig['max_connections'], decode_responses=True)
            self.redisCli = Redis(connection_pool=self.redis_pool)
        except Exception as e:
            print(e)
            self.redisCli = None

    # 请求接口获取数据
    def reqSvr(self, method, url, headers=None, data=None, params=None):
        try:
            response = requests.request(method, url=url, headers=headers, data=data, params=params)
            if response.status_code == 200:
                ret = response.content.decode("utf-8")
                return ret
            else:
                return []
        except Exception as e:
            print(e)
            return None

    @staticmethod
    def getSqlText(path, params):
        try:
            if 'txt' not in path:
                path = './datas/sqls/' + path + '.txt'
            with open(path, 'rb') as f:
                items = f.readlines()
                s = ''
                for item in items:
                    s += str(item, encoding="utf-8").replace('\r\n', '')
                res = s
                for key in params.keys():
                    if isinstance(params[key], str):
                        res = s.replace(':' + key, "'" + params[key] + "'")
                    elif isinstance(params[key], int):
                        res = s.replace(':' + key, params[key])
                return res
        except Exception as e:
            print(e)
            return None

    def getFileJson(self, path):
        c = self.req.replace('', '')
        try:
            with open(path, 'rb') as f:
                fileJson = json.load(f)
                fileJson['requestId'] = c
                return fileJson
        except Exception as e:
            with open(self.default, 'rb') as f:
                fileJson = json.load(f)
                fileJson['requestId'] = c
                return fileJson

    # 构造返回数据的格式
    def resData(self, data, status):
        self.resFormat = {}
        if status == 'OK':
            if isinstance(data, int):
                self.resFormat['body'] = data
                self.resFormat['requestId'] = self.req.replace('', '')
                self.resFormat['status'] = status
                return self.resFormat
            elif isinstance(data[-1], dict):
                if len(data[-1]) == 1 and 'total' in data[-1]:
                    self.resFormat['body'] = data[:-1]
                    self.resFormat['total'] = data[-1]['total']
                else:
                    self.resFormat['body'] = data
                self.resFormat['requestId'] = self.req.replace('', '')
                self.resFormat['status'] = status
                return self.resFormat
        else:
            self.resFormat['errorMessage'] = data
            self.resFormat['requestId'] = self.req.replace('', '')
            self.resFormat['status'] = status
            return self.resFormat

    # 获取请求参数
    def getReqParams(self, request):
        res = {}
        try:
            query = request.args.to_dict()
            form = request.form.to_dict()
            body = request.json
            if query:
                res['query'] = query
            if form:
                res['form'] = form
            if body:
                res['json'] = body
            return res
        except Exception as e:
            print(e)
            return e

    # redis处理
    def RedisOperate(self):
        '''
            字符串
            集合
            有序集合
            哈希
            列表
        '''
        try:
            if self.redisCli:
                print(self.redisCli.get('test').decode('utf-8'))
        except Exception as e:
            print(e)


if __name__ == '__main__':
    obj = {
        "start": "'2022-06-01'",
        "end": "'2022-06-03'",
        "mn": "HC622421051052"
    }
    res = aUtils.reqSvr('POST', 'http://ai.seedlight.cn:31341/rest/sql/seed2022',
                        {'Authorization': 'Basic cm9vdDp0YW9zZGF0YQ=='},
                        'select * from d_img limit 0,20 ')
    res = json.loads(res)
    headList = res['head']
    datas = res['data']
    print(res['head'])
    print(res['data'])
    ret = []
    for item in datas:
        test = dict(zip(headList, item))
        ret.append(test)
    print(ret)
    print(len(ret))
